class Solution {
 public:
  int islandPerimeter(vector<vector<int>>& grid) {
    if (grid.empty() || grid[0].empty()) return 0;
    int lenght = grid.size(), wight = grid[0].size(), res = 0;
    for (int i = 0; i < lenght; ++i) {
      for (int j = 0; j < wight; ++j) {
        if (grid[i][j] == 0) continue;
        if (j == 0 || grid[i][j - 1] == 0) ++res;
        if (i == 0 || grid[i - 1][j] == 0) ++res;
        if (j == wight - 1 || grid[i][j + 1] == 0) ++res;
        if (i == lenght - 1 || grid[i + 1][j] == 0) ++res;
      }
    }
    return res;
  }
};